/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectController
 * 项目立项
 *
 * 修改纪录
 * 2020-12-25 版本：1.0 lanjianwei 创建。
 * @version 版本：1.0
 * @author 作者：lanjianwei
 * 创建日期：2020-12-25
 */

package com.topscomm.mpm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.Config;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboExcelExportTaskService;
import com.topscomm.cbo.service.ICboOrgService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.main.hessian.IBaseOperateRecordService;
import com.topscomm.main.hessian.IMmsDeptExtraInfoService;
import com.topscomm.mis.pojo.MisDeptHeaderEntity;
import com.topscomm.mis.service.impl.MisDeptHeaderService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.controller.auto.MpmProjectControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectCirculatedEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectResourcePoolEntity;
import com.topscomm.mpm.pojo.MpmProjectTaskEntity;
import com.topscomm.mpm.service.IMpmProjectCirculatedService;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.mpm.utils.ConvertTimeUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.ParameterCache;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: lanjianwei
 * @date: 2020-12-25
 * @description:项目立项Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/project")
public class MpmProjectController extends MpmProjectControllerAuto implements IMpmProjectController {
	@Resource(name = "cboOrgService")
	private ICboOrgService cboOrgService;
	@Resource(name = "mpmProjectSaleService")
	private MpmProjectSaleService mpmProjectSaleService;
	@Resource(name = "misDeptHeaderService")
	private MisDeptHeaderService misDeptHeaderService;
	@Autowired
	private IMpmProjectCirculatedService mpmProjectCirculatedService;
	@Resource(name = "cboUserService")
	private ICboUserService cboUserService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	MpmProjectPolymerizationController mpmProjectPolymerizationController;
	@Autowired
	IBaseOperateRecordService baseOperateRecordService;
	@Autowired
	MpmProjectTaskService mpmProjectTaskService;
	@Autowired
	private MpmProjectResourcePoolService mpmProjectResourcePoolService;
	@Autowired
	private IMmsDeptExtraInfoService mmsDeptExtraInfoService;
	@Autowired
	private MpmProjectService mpmProjectService;
	@Autowired
	private MpmProjectProductInfoService mpmProjectProductInfoService;
	@Autowired
	private MpmProjectTaskController mpmProjectTaskController;
	@Autowired
	private MpmProjectPolymerizationService mpmProjectPolymerizationService;
	/**
	 * @author: lanjianwei
	 * @date: 2020-12-25
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_projectname")) {
			String value = paraMap.get("qry_projectname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectname like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_nameorcode")) {
			String value = paraMap.get("qry_nameorcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (projectcode like '%{0}%' or projectname like '%{0}%') ", value);
		}
		if (paraMap.containsKey("qry_projectlevel")) {
			String value = paraMap.get("qry_projectlevel").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectlevel in ({0})", value);
		}
		if (paraMap.containsKey("qry_projectmanagercode")) {
			String value = paraMap.get("qry_projectmanagercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagercode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_projectmanager")) {
			String value = paraMap.get("qry_projectmanager").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (projectmanager like '%{0}%' or projectmanagercode = '{0}') ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state in ({0})", value);
		}
		if (paraMap.containsKey("qry_projectstate")) {
			String value = paraMap.get("qry_projectstate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate in ({0})", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
/*		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
				String deptcodes_header = ConvertUtil
						.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
				if (StringUtil.isEmpty(deptcodes_header))
					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )",
							this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(),
							this.getUserBean().getWorkDept().getCode());
				else
					sql.appendSingle(
							" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )",
							deptcodes_header, this.getUserBean().getUser().getCode(),
							this.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}*/
        // 套用旧项目参照使用的查询条件
		if (paraMap.containsKey("qry_projectref")) {
			String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(getUserBean().getDept().getCode());
			sql.appendSingle(" and projectstate in (2,8) and (projectmanagercode='{0}' or open='1' or deptcommoncode='{1}') ", getUserBean().getUser().getCode(), deptCommonCode);
		}
		return sql.toString();
	}

	/**
	 * @author: lanjianwei
	 * @date: 2020-12-25
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: lanjianwei
	 * @date: 2020-12-25
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目立项申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"),
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	/**
	 *
	 * @description: 部门关联组织接口
	 * @param paraMap
	 * @author: wushenghong
	 * @date: 2020-05-11
	 * @modify:
	 */
	@GetMapping(value = "/queryOrgByDeptId")
	public ResponseResult<Object> queryOrgByDeptId(@RequestParam Map<String, Object> paraMap) {
		String deptId = ConvertUtil.convertToString(paraMap.get("deptId"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("id in (select orgid from cbodept where id = {0})", deptId);
		List<CboOrgEntity> cboOrgEntityList = cboOrgService.queryByWhere(sql.toString());
		CboOrgEntity resultEntity = cboOrgEntityList.size() > 0 ? cboOrgEntityList.get(0) : (new CboOrgEntity());
		return ResponseResult.ok(resultEntity);
	}




	/**
	 * @Title: mainListExtraData
	 * @description: 手机端接口添加销售表数据项
	 * @param paraMap
	 * @param mainListData
	 * @author: lanjianwei
	 * @date: 2021年1月21日上午11:09:31
	 * @modify:
	 */
	@Override
	public void mainListExtraData(Map<String, Object> paraMap, Map<String, Object> mainListData) {
		Map<String, Object> dataMapsale = mpmProjectSaleService.queryMapById(paraMap.get("id").toString());
		if (!dataMapsale.isEmpty()) {
			String participatemoneyStr = ConvertUtil.convertToString(dataMapsale.get("participatemoney"));
			dataMapsale.put("participatemoney",formatMonty(participatemoneyStr,9,2));
			mainListData.putAll(dataMapsale);
		}
		//涉及产品范围
		List<Map<String, Object>> productList = mpmProjectProductInfoService.queryMapByWhere(" projectid = '" + ConvertUtil.convertToString(paraMap.get("id")) + "'");
		StringBufferProxy productInfoPorxy = new StringBufferProxy();
		if (!CollectionUtil.isEmpty(productList)) {
			for (Map map : productList) {
				//产品名称，线索显示产品大类，机会点显示产品中类
				String cboItemCode = MpmSystemConst.MpmProjectSource.lead.equals(ConvertUtil.convertToString(dataMapsale.get("projectsource"))) ? "ProductCatalog1" : "ProductCatalog2";
				String product = datacodeCache.getValueDynamic(cboItemCode, ConvertUtil.convertToString(map.get("productcode")),"code", "name");
				//产品金额
				String money = ConvertUtil.convertToString(map.get("fund"));
				if (money.length() > 0) {
					//金额格式化 追加万元
					money = formatMonty(money, 9, 2);
				}
				productInfoPorxy.appendLineSingle(product + "-" + money);
			}
		}
		mainListData.put("productrange", productInfoPorxy.toString());
	}
	/**
	 * @author: wudaliang
	 * @date: 2021-06-22
	 * @param: value
	 * @param: maxDigit
	 * @param: minDigit
	 * @description:格式化金额
	 * @return: java.lang.String
	 * @modify:
	 */
	protected String formatMonty(String value, int maxDigit, int minDigit) {
		if (value != null && !value.equals("")) {
			try {
				BigDecimal bigDecimal = new BigDecimal(value);
				NumberFormat currency = NumberFormat.getNumberInstance();
				currency.setMaximumFractionDigits(maxDigit);
				currency.setMinimumFractionDigits(minDigit);
				String s = currency.format(bigDecimal.doubleValue());
				value = s + "万元";
				return value;
			} catch (Exception var7) {
				return value;
			}
		} else {
			return "";
		}
	}


	/**
	 * @Title: changeList
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @throws Exception
	 * @date: 2021年1月27日上午10:23:50
	 * @modify:
	 */
	@GetMapping(value = "/changeList")
	public ResponseResult<Object> changeList(@RequestParam(required = false) Map<String, Object> paraMap)
			throws Exception {
		String projectsource = ConvertUtil.convertToString(paraMap.get("projectsource"));
		// 查询本地数据库获取机会点信息
		if ("1".equals(ParameterCache.getValue("MPMQueryLTCByLocal"))) {
			Query query = new Query(paraMap);
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex", query.getCurrentPage());
			int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
			paraMap2.put("begincount", beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", "a.code");
			paraMap2.put("sord", query.getSord());
			// 使用平台拦截器分页
			paraMap2.put("IsNeedPage", "true");
			Map<String, Object> countParamMap = new HashMap<>();
			countParamMap.put("usercode", paraMap.get("usercode"));
			paraMap2.put("usercode", paraMap.get("usercode"));
			countParamMap.put("qry_chancecode", paraMap.get("qry_chancecode"));
			paraMap2.put("qry_chancecode", paraMap.get("qry_chancecode"));
			if (paraMap.containsKey("origincode")) {
				String origincode = ConvertUtil.convertToString(paraMap.get("origincode")).replaceAll(",", "','");
				countParamMap.put("qry_origincode", origincode);
				paraMap2.put("qry_origincode", origincode);
			}
			int totalCount = 0;
			if ("1".equals(projectsource)) {
				totalCount = this.service.getCount(countParamMap, "getCountOfLeadBackBone");
				tempList = this.service.queryMap(paraMap2, "queryLeadBackBone");
			} else if ("2".equals(projectsource)) {
				totalCount = this.service.getCount(countParamMap, "getCountOfChanceBackBone");
				tempList = this.service.queryMap(paraMap2, "queryChanceBackBone");
			}
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} else {
			SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
			requestFactory.setConnectTimeout(2000);// 设置超时
			requestFactory.setReadTimeout(100000);// 读取超时时间
			RestTemplate restTemplate = new RestTemplate(requestFactory);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			String token = ParameterCache.getValue("MPM_Token");
			String templateid = "";
			// 查询线索
			if ("1".equals(projectsource)) {
				templateid = ParameterCache.getValue(MpmSystemConst.MPM_Query_Lead);
			} else if ("2".equals(projectsource)) {
				templateid = ParameterCache.getValue(MpmSystemConst.MPM_Query_Change);
			}
			headers.set("token", token);
			JSONObject map = new JSONObject();
			map.put("templateid", templateid);
			String url = ParameterCache.getValue("MPM_QueryUrl");
			JSONObject params = new JSONObject();
			params.put("usercode", paraMap.get("usercode"));
			map.put("paramsMap", params);
			// 设置分页查询
			int pageSize = 10;
			map.put("pageNum", paraMap.get("currentPage"));
			map.put("pageSize", paraMap.get("pageSize"));

			HttpEntity<JSONObject> request = new HttpEntity<>(map, headers);
			ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);

			if (response.getBody().getBooleanValue("success") == true) {
				int totalCount = response.getBody().getJSONObject("result").getIntValue("totalCount");
				pageSize = response.getBody().getJSONObject("result").getIntValue("pageSize");
				int currentPage = response.getBody().getJSONObject("result").getIntValue("currentPage");
				JSONArray dataList = response.getBody().getJSONObject("result").getJSONArray("dataList");
				List<Map> list = new ArrayList<Map>();
				list = JSONObject.parseArray(dataList.toJSONString(), Map.class);
				Query query = new Query(paraMap);
				Page page = new Page(dataList, totalCount, pageSize, currentPage);
				return ResponseResult.ok(page);
			} else {
				if ("1".equals(projectsource)) {
					throw new Exception("获取线索数据失败，请联系管理员！");
				} else {
					throw new Exception("获取机会点数据失败，请联系管理员！");
				}
			}
		}
	}


	@Override
	@PutMapping(value = "/approval")
	public ResponseResult<Object> approval(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			// 执行审批操作
			String approvalOpinion = paraMap.get("approvalopinion").toString();
			String approvalType = paraMap.get("approvaltype").toString();
			String nodeInsId = paraMap.get("nodeinsid").toString();
			String sourceid = paraMap.get("sourceid").toString();
			String backNodeId = ConvertUtil.convertToString(paraMap.get("backnodeid"));
			long nextUserId = 0;
			if (paraMap.containsKey("nextuserid") && !StringUtil.isEmpty(paraMap.get("nextuserid").toString())) {
				nextUserId = Long.parseLong(paraMap.get("nextuserid").toString());
			}
			if("".equals(approvalOpinion)&&"1".equals(approvalType)){
				approvalOpinion="同意";
			}
			if("2".equals(approvalType)){
				HashMap<String, Object> map = new HashMap<>();
				map.put("id",sourceid);
				map.put("projectstate",3);
				this.update(map);
			}
			this.service.executeApprove(nodeInsId, new Date(), approvalOpinion, approvalType, backNodeId,
				this.getUserBean(), nextUserId);
			return ResponseResult.ok("操作成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-07-08
	 * @param: paraMap
	 * @description: 返回林总和省总信息
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@GetMapping("/queryCeo")
	public ResponseResult<Object> queryCeo(
		@RequestParam(required = false) Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		String managercode = "";
		if (paraMap.containsKey("managercode")) {
			//managercode为项目经理工号
			managercode = ConvertUtil.convertToString(paraMap.get("managercode"));
		} else {
			MpmProjectEntity entity = this.service.queryById(paraMap.get("projectid").toString());
			managercode = entity.getProjectmanagercode();
		}
		sql.appendSingle("  ID =(SELECT DEPTID from CBOUSER WHERE CODE='{0}') AND ENABLED=1 ", managercode);
		String code = cboDeptService.queryByWhere(sql.toString()).get(0).getCode();
		MisDeptHeaderEntity misDeptHeaderEntity = null;
		if (code.contains("_")) {
			sql.clear();
			sql.appendSingle("deptcode ='{0}' and category = 'CEO'", code.substring(0, code.indexOf('_') + 5));
			misDeptHeaderEntity = misDeptHeaderService.queryByWhere(sql.toString()).get(0);
		} else {
			sql.clear();
			sql.appendSingle("deptcode ='{0}' and category = 'CEO'", code.substring(0, 4));
			misDeptHeaderEntity = misDeptHeaderService.queryByWhere(sql.toString()).get(0);
		}
		List<MisDeptHeaderEntity> list = new ArrayList<>();
		sql.clear();
		sql.appendSingle("usercode ='0070' ");
		MisDeptHeaderEntity misDeptHeaderEntity1 = misDeptHeaderService.queryByWhere(sql.toString())
			.get(0);
		// 如果项目经理的领导是林总，需要去重
		if(misDeptHeaderEntity!=null&&misDeptHeaderEntity1!=null&&misDeptHeaderEntity.getUsercode().equals(misDeptHeaderEntity1.getUsercode())){
			list.add(misDeptHeaderEntity);
		}else{
			list.add(misDeptHeaderEntity);
			list.add(misDeptHeaderEntity1);
		}
		return ResponseResult.ok(list);

	}

	/**
	 * @author: chengengwei
	 * @date: 2021-07-14
	 * @description: 判断项目是否有传阅反馈记录
	 * @modify:
	 */
	@GetMapping("/checkCirculatedRecord")
	public ResponseResult<Object> checkCirculatedRecord(@RequestParam(required = false) Map<String, Object> paraMap){
		String code = ConvertUtil.convertToString(paraMap.get("code"));
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendSingle(" {0} = '{1}' ", MpmProjectCirculatedEntity.FieldProjectcode, code);
		List<MpmProjectCirculatedEntity> entities = this.mpmProjectCirculatedService.queryByWhere(whereSql.toString());
		Map<String, Object> resultMap = new HashMap<>();
		if (entities.size() > 0) {
			resultMap.put("hasrecord", true);
			resultMap.put("circulatedrecord", entities.get(0));
		} else {
			resultMap.put("hasrecord", false);
		}
		return ResponseResult.ok(resultMap);
	}

	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		// 获取决策人员的二级部门
		if (paraMap.containsKey(MpmProjectEntity.FieldDecisionusercode)) {
			String decisionUserCode = ConvertUtil.convertToString(paraMap.get(MpmProjectEntity.FieldDecisionusercode));
			if (!StringUtil.isEmpty(decisionUserCode)) {
				StringBufferProxy sql = new StringBufferProxy();
				String code = Arrays.stream(decisionUserCode.split(",")).filter(item -> !StringUtil.isEmpty(item)).map(item -> "'" + item + "'").collect(Collectors.joining(","));
				sql.appendSingle(CboUserEntity.FieldCode + " in ({0})", code);
				List<CboUserEntity> userList = cboUserService.queryByWhere(sql.toString());
				Set<Long> deptIdSet = new HashSet<>();
				String deptIdStr = userList.stream().map(CboUserEntity::getDeptid).filter(item -> {
					if (deptIdSet.contains(item)) {
						return false;
					}
					else {
						deptIdSet.add(item);
						return true;
					}
				}).map(item -> "'" + item + "'").collect(Collectors.joining(","));
				List<CboDeptEntity> deptList = cboDeptService.queryByIds(deptIdStr);
				String dispDecisionUserDeptName = deptList.stream().map(CboDeptEntity::getFullname).map(item -> {
					String[] split = item.split("\\\\");
					return split.length > 1 ? split[1] : (split.length > 0 ? split[0] : "");
				}).collect(Collectors.joining("、"));
				paraMap.put("dispdecisionuserdeptname", dispDecisionUserDeptName);
			}
		}
		// 获取sale表信息
		Map<String, Object> dataMapsale = mpmProjectSaleService.queryMapById(paraMap.get("id").toString());
		paraMap.putAll(dataMapsale);
	}
	/**
	 * @author: 王兴华
	 * @date: 2021-07-14
	 * @description: 邀请决策
	 * @modify:
	 */
	@PutMapping("/updateInvitedUser")
	public ResponseResult<Object> updateInvitedUser(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			// 有邀请人的情况
			if (!StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get("invitedecisionusername")))) {
				List<String> invitedUsers =  Arrays.asList(ConvertUtil.convertToString(paraMap.get("invitedecisionusername")).split(","));
				List<String> invitedCodes = Arrays.asList(ConvertUtil.convertToString(paraMap.get("invitedecisionusercode")).split(","));
				// 获取原始单据
				Map<String,Object> originalMap = this.service.queryMapById(ConvertUtil.convertToString(paraMap.get("id")));
				List<String> orginalUsers = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusername")).split(","));
				List<String> orginalCodes = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusercode")).split(","));
				// 遍历姓名去重
				List<String> useUserName = new ArrayList<>();
				for (int i = 0; i < invitedUsers.size(); i++) {
					if(!orginalUsers.contains(invitedUsers.get(i))) {
						useUserName.add(invitedUsers.get(i));
					}
				}
				// 工号去重
				List<String> useUserCode = new ArrayList<>();
				for (int i = 0; i < invitedCodes.size(); i++) {
					if (!orginalCodes.contains(invitedCodes.get(i))) {
						useUserCode.add(invitedCodes.get(i));
					} else {
						throw new ServiceException("邀请人已包含在决策组成员中，请重新选择");
					}
				}
				// 邀请人员
				String users = useUserName.stream().collect(Collectors.joining(","));
				String decisionusername = useUserName.size() > 0 ?
						ConvertUtil.convertToString(originalMap.get("decisionusername")) + "," + users :
						ConvertUtil.convertToString(originalMap.get("decisionusername"));
				// 邀请人员工号
				String codes = useUserCode.size() > 0 ?
						"," + useUserCode.stream().collect(Collectors.joining(",")) + "," : "";
				String decisionusercode = useUserCode.size() > 0 ?
						ConvertUtil.convertToString(originalMap.get("decisionusercode")) + codes.substring(1) :
						ConvertUtil.convertToString(originalMap.get("decisionusercode"));
				paraMap.put("decisionusercode", decisionusercode);
				paraMap.put("decisionusername", decisionusername);
				paraMap.put("invitedecisionusername", users);
				paraMap.put("invitedecisionusercode", codes);
			} else {
				// 删除值为空的key
				Iterator<String> keySetIterator = paraMap.keySet().iterator();
				while (keySetIterator.hasNext()) {
					if (StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get(keySetIterator.next())))) {
						keySetIterator.remove();
					}
				}
			}
			this.service.update(paraMap);
			return ResponseResult.ok("修改成功");
		} catch (Exception var3) {
			return this.handleControllerException(var3);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2021-08-23
	 * @description: 获取项目经理/部门的统计数据
	 * @modify:
	 */
	@GetMapping("/getSummaryList")
	public ResponseResult<Object> getSummaryList(@RequestParam(required = false) Map<String,Object> paraMap){
		List<Map<String, Object>> result = getSummaryData(paraMap);
		return ResponseResult.ok(result);
	}
	//查询数据库表，获取统计数据
	public List<Map<String,Object>> getSummaryData(Map<String,Object> paraMap){
		List<Map<String,Object>> res;
		String sql = "";
		if (paraMap.containsKey("qry_purchasepattern")) {
			sql = mpmProjectPolymerizationController.spellListForSys(paraMap);
		} else {
			sql = mpmProjectPolymerizationController.existsSqlForQuery(paraMap, MpmProjectEntity.tableName, MpmProjectEntity.FieldProjectcode);
		}
        paraMap.put("whereSql",sql);
		//判断按项目经理统计还是按部门统计,请求不同的sql语句
			if (MpmSystemConst.MPM_Query_Manager.equals(paraMap.get("sourceType"))) {
				res = service.queryMap(paraMap, "getSummaryListManager");
			} else if (MpmSystemConst.MPM_Query_Dept.equals(paraMap.get("sourceType"))) {
				res = service.queryMap(paraMap, "getSummaryListDept");
			} else {
				throw new ServiceException("统计维度未知，请联系管理员");
			}
			if (res.size() > 0) {
				Set<String> fieldSet = new HashSet<String>(res.get(0).keySet());
				service.setDispFields(res);
				Map<String, Object> totalMap = new HashMap<>();
				fieldSet.forEach(field -> {
					totalMap.put(field, new BigDecimal(0));
				});
				totalMap.put("dispprojectmanagercode", "合计");
				totalMap.put("deptname", "合计");
				res.stream().forEach((map)->{
					fieldSet.forEach((str)-> {
						if (!(MpmProjectEntity.FieldDeptname.equals(str) || MpmProjectEntity.FieldProjectmanagercode.equals(str))) {
							// 每条记录该字段值
							BigDecimal fieldValue = ConvertUtil.convertToBigDecimal(map.get(str));
							// 合计记录该字段值
							BigDecimal totalValue = ConvertUtil.convertToBigDecimal(totalMap.get(str));
							totalMap.put(str, fieldValue.add(totalValue));
						}
					});
				});
				res.add(totalMap);
			}
		return res;
	}
	//项目经理的excel表格自动生成
	@PostMapping({"/exportBigExcel"})
	public ResponseResult<Object> exportBigExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		String cols = ConvertUtil.convertToString(paraMap.get("cols"));
		String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
		fileName = fileName.length() == 0 ? "导出数据.xlsx" : fileName + ".xlsx";
		try {
			exportExcelXlsx(response, (ITapService)this.service, paraMap, "", fileName, cols, this.getUserBean().getUser().getId());
			return null;
		} catch (Exception var11) {
			return this.handleControllerException(var11);
		}
	}
	//导出excel
	private void exportExcelXlsx(HttpServletResponse response, ITapService cboService, Map<String, Object> paraMap, String queryMybatisMapper, String fileName, String columns, long userId) throws Exception {
		InputStream inputStream = null;
		int len;
		List<Map<String,Object>> listDataMap = getSummaryData(paraMap);
		inputStream = OfficeOperateUtil.exportExeclXlsx(listDataMap, columns.split(","));
		if (inputStream != null) {
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("istaskexport", "0");
			response.setHeader("Access-Control-Expose-Headers", "istaskexport");
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];

			while((len = inputStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}

			inputStream.close();
		} else {
			CboExcelExportTaskEntity cboExcelExportTaskEntity = new CboExcelExportTaskEntity();
			cboExcelExportTaskEntity.setName(fileName);
			cboExcelExportTaskEntity.setColnames(columns);
			cboExcelExportTaskEntity.setExportuserid(userId);
			cboExcelExportTaskEntity.setFilename(fileName);
			cboExcelExportTaskEntity.setQuerymapper(queryMybatisMapper);
			cboExcelExportTaskEntity.setQueryparams(JSONUtil.toJSONString(paraMap));
			String serviceName = cboService.getClass().getSimpleName();
			serviceName = serviceName.substring(0, serviceName.indexOf("$"));
			char[] chars = serviceName.toCharArray();
			chars[0] = (char)(chars[0] + 32);
			cboExcelExportTaskEntity.setServicename(String.valueOf(chars));
			ICboExcelExportTaskService cboExcelExportTaskService = (ICboExcelExportTaskService)SpringUtil.getBean("cboExcelExportTaskService");
			cboExcelExportTaskService.insert(cboExcelExportTaskEntity);
			response.setHeader("istaskexport", "1");
			response.setHeader("Access-Control-Expose-Headers", "istaskexport");
		}
	}

	/**
	 * @author: chengengwei
	 * @date: 2021-08-25
	 * @description: 按产品线统计
	 * @modify:
	 */
	@GetMapping("/getProductLineSummaryList")
	public ResponseResult<Object> getProductLineSummaryList(@RequestParam(required = false) Map<String,Object> paraMap) {
		try {
			String sql = "";
			List<Map<String, Object>> resultList = this.service.getProductLineSummaryList(sql);
			return ResponseResult.ok(resultList);
		} catch (Exception e) {
			return this.handleControllerException(e);
		}
	}

	/**
	 * @description:导出产品线统计Excel
	 * @author: chengengwei
	 * @date: 2021-08-27
	 * @modify:
	 */
	@PostMapping(value = "/exportProductBigExcel")
	public void exportProductBigExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String whereSql = mpmProjectPolymerizationController.existsSqlForQuery(paraMap, "MPMPROJECT", "PROJECTCODE");
			List<Map<String, Object>> dataList = this.service.getProductLineSummaryList(whereSql);
			String cols = "productlinename;产品线,doinga;进行中（A级）,donea;已完结（A级）,funda;产品金额（万元）（A级）," +
					"doingb;进行中（B级）,doneb;已完结（B级）,fundb;产品金额（万元）（B级）," +
					"doingc;进行中（C级）,donec;已完结（C级）,fundc;产品金额（万元）（C级）," +
					"doingd;进行中（D级）,doned;已完结（D级）,fundd;产品金额（万元）（D级）,";
			String[] colArray = cols.split(",");
			InputStream inStream = OfficeOperateUtil.exportExeclXlsx(dataList, colArray);
			String fileName = "数据统计——按产品线.xlsx";
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			// 暴露自定义的首部,供页面资源使用
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}

	/**
	 * @description:判断项目在决策组审批节点是否被退回
	 * @author: zhangjunyao
	 * @date: 2021-11-19
	 * @modify:
	 */
	@GetMapping(value = "/ifApprovalBack")
	public ResponseResult<Object> ifApprovalBack(@RequestParam(required = false) Map<String, Object> paraMap) {
		return ResponseResult.ok(this.service.ifApprovalBack(paraMap));
	}
	/**
	 * @description:判断用户是否为CFO
	 * @author: houyuhang
	 * @date: 2021-11-18
	 * @modify:
	 */
	@GetMapping("/isCFO")
	public ResponseResult<Object> isCFO(@RequestParam(required = false) Map<String,Object> paraMap){
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" select id from mmsdeptextrainfo where cfocode = '{0}' ", paraMap.get("usercode"));
	    int count = this.service.selectExecute(sql.toString()).size();
		if(count > 0) {
			return ResponseResult.ok(true);
		} else {
			return ResponseResult.ok(false);
		}
	}
	/**
	 * @description:根据projectcode查询主表id
	 * @author: houyuhang
	 * @date: 2021-02-16
	 * @modify:
	 */
	@GetMapping("/queryMpmProjectid")
	public ResponseResult<Object> queryMpmProjectid(@RequestParam(required = false) Map<String,Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" projectcode = '{0}' ",paraMap.get("projectcode"));
			List<MpmProjectEntity> mpmProjectEntities = this.service.queryByWhere(sql.toString());
			if(mpmProjectEntities.size() == 0) {
				throw new ServiceException("没有找到项目！");
			}
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("id", mpmProjectEntities.get(0).getId());
			return ResponseResult.ok(dataMap);
		} catch (Exception e) {
			return this.handleControllerException(e);
		}
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2022-03-26
	 * @description: 实时更新项目异常状态
	 * @modify:
	 */
	@PutMapping(value = "/updateAbnormalState")
	public ResponseResult<Object> updateAbnormalState(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			if (paraMap.containsKey(MpmProjectEntity.FieldProjectcode)) {
				resultMap = this.service.updateAbnormalState(ConvertUtil.convertToString(paraMap.get(MpmProjectEntity.FieldProjectcode)));
			}
			return ResponseResult.ok(resultMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	@PostMapping(value = "/operateMarkState")
	public ResponseResult<Object> operateMarkState(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String sourceid = ConvertUtil.convertToString(paraMap.get("sourceid"));
			String sourcetype = ConvertUtil.convertToString(paraMap.get("sourcetype"));
			if (StringUtil.isEmpty(sourceid) || StringUtil.isEmpty(sourcetype)) {
				return ResponseResult.error("参数错误！");
			}
			baseOperateRecordService.changeOperateMarkState(paraMap,getUserBean());
			this.service.sendFocusMessage(paraMap);
			return ResponseResult.ok("操作成功");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	@GetMapping(value = "/queryMarkedInfo")
	public ResponseResult<Object> queryMarkedInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String sourceid = ConvertUtil.convertToString(paraMap.get("projectId"));
			String sourcetype = ConvertUtil.convertToString(paraMap.get("sourcetype"));
			// 查询对应任务
			List<MpmProjectTaskEntity> taskEntities = mpmProjectTaskService.queryByWhere(" projectcode in (select projectcode from MpmProject where id = "+sourceid+")");
			String taskIds = taskEntities.stream().map(item->ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
			String markedperson = baseOperateRecordService.queryMarkedInfo(sourcetype,sourceid,taskIds);
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("markedperson",markedperson);
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	 * @description:判断切换后的人员是否在当前等级下可以被选中
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年05月19日
	 * @modify:
	 */
	@GetMapping(value = "/judgeDecisionUser")
	public ResponseResult<Object> judgeDecisionUser(@RequestParam(required = false) Map<String,Object> paraMap) {
		try {
			String decisionusercode = ConvertUtil.convertToString(paraMap.get("decisionusercode"));
			String decisionusername = ConvertUtil.convertToString(paraMap.get("decisionusername"));
			Map<String, Object> resultMap = new HashMap<>();
			StringBufferProxy sql = new StringBufferProxy();
			// 判断切换后的人员是否在当前等级下可以被选中
			sql.appendSingle(" instr('{0}', {1}) > 0 and projectlevel not like '%{2}%' ", decisionusercode,
					SQLAdapter.concat(new String[]{"','", MpmProjectResourcePoolEntity.FieldUsercode , "','"}), ConvertUtil.convertToString(paraMap.get("newlevel")));
			List<MpmProjectResourcePoolEntity> mpmProjectResourcePoolEntities = mpmProjectResourcePoolService.queryByWhere(sql.toString());
			if (CollectionUtil.isEmpty(mpmProjectResourcePoolEntities)) {
				resultMap.put("newdecisionusercode", decisionusercode);
				resultMap.put("newdecisionusername", decisionusername);
			}
			List<String> decisionusercodeList = Arrays.stream(decisionusercode.split(",")).filter(item -> !StringUtil.isEmpty(item)).collect(Collectors.toList());
			List<String> decisionusernameList = Arrays.stream(decisionusername.split(",")).filter(item -> !StringUtil.isEmpty(item)).collect(Collectors.toList());
			for(MpmProjectResourcePoolEntity mpmProjectResourcePoolEntity : mpmProjectResourcePoolEntities) {
				decisionusercodeList.remove(mpmProjectResourcePoolEntity.getUsercode());
				decisionusernameList.remove(mpmProjectResourcePoolEntity.getUsername());
			}
			resultMap.put("newdecisionusercode", CollectionUtil.isEmpty(decisionusercodeList) ? "" : "," + decisionusercodeList.stream().collect(Collectors.joining(",")) + ",");
			resultMap.put("newdecisionusername", CollectionUtil.isEmpty(decisionusernameList) ? "" : decisionusernameList.stream().collect(Collectors.joining(",")));
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	@GetMapping(value = "/queryIsPMO")
	public ResponseResult<Object> queryIsPMO(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String deptcode = this.getUserBean().getDept().getCode();
			boolean ispmo = false;
			if (MpmSystemConst.PMODeptcode.contains("," + deptcode.substring(0, 4) + ",")) {
				ispmo = true;
			}
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("ispmo", ispmo);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	 * @description:判断用户是否为国网、南网或经营管理部PMO，可以进行关注与留言 若为国网、南网 可以进行导出项目任务明细
	 * @author: houyuhang
	 * @date: 2022年07月05日
	 * @modify:
	 */
	@GetMapping(value = "/queryCanWatch")
	public ResponseResult<Object> queryCanWatch(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String canWatchRole = MpmSystemConst.CanWatchRole;
			String JYGLBRole = MpmSystemConst.JYGLBRole;
			String canExportRole = MpmSystemConst.CanExportRole;
			boolean canWatch = false;
			boolean whetherpmo = false;
			boolean canExport = false;
			// 如果当前用户的角色列表中包含任意一个系统参数中配置角色,可以进行关注与留言
			List<CboRoleEntity> roleList = this.getUserBean().getRoleList();
			for (CboRoleEntity role : roleList) {
				// 排除角色code为空的情况
				if (StringUtil.isEmpty(role.getCode())) {
					continue;
				}
				if (canWatchRole.contains("," + role.getCode() + ",")) {
					canWatch = true;
					break;
				}
			}
			for(CboRoleEntity roleEntity:roleList) {
				// 排除角色code为空的情况
				if (StringUtil.isEmpty(roleEntity.getCode())) {
					continue;
				}
				if (JYGLBRole.contains("," + roleEntity.getCode() + ",")) {
					whetherpmo = true;
					break;
				}
			}
			for(CboRoleEntity roleEntity:roleList) {
				// 排除角色code为空的情况
				if (StringUtil.isEmpty(roleEntity.getCode())) {
					continue;
				}
				if (canExportRole.contains("," + roleEntity.getCode() + ",")) {
					canExport = true;
					break;
				}
			}
			String deptcommcodes = mmsDeptExtraInfoService.getCfoDeptCodes(getUserBean().getUser().getCode());
			resultMap.put("canwatch", canWatch);
			resultMap.put("deptcommcodes", deptcommcodes);
			resultMap.put("whetherpmo", whetherpmo);
			resultMap.put("canexport", canExport);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 立项置顶功能
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2022/8/9 14:31
	 * @modify:
	 */
	@PutMapping({"/changeTop"})
	public ResponseResult<Object> changeTop(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			return ResponseResult.ok(this.service.changeTop(paraMap));
		} catch (Exception e) {
			return this.handleControllerException(e);
		}
	}
	/***
	 * @description: 项目编号增加春季、秋季攻势前缀(春季 1;秋季 2; 无 null)
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2022/10/12
	 * @modify:
	 */
	@PutMapping({"/addProjectAttackFirst"})
	public ResponseResult<Object> addProjectAttackFirst(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
			String param = ConvertUtil.convertToString(paraMap.get("projectattack"));
			this.service.addProjectAttackFirst(projectcode, param);
			return ResponseResult.ok("修改成功");
		} catch (Exception e) {
			return this.handleControllerException(e);
		}
	}
	/***
	 * @description: 获取mpmproject和sale表信息
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2022/11/14
	 * @modify:
	 */
	@GetMapping(value= "/queryProjectInfo")
	public ResponseResult<Object> queryProjectInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			Map<String, Object> dataMap = this.service.queryMapById(id);
			Map<String, Object> dataMapsale = mpmProjectSaleService.queryMapById(id);
			dataMapsale.putAll(dataMap);
			dataMap = dataMapsale;
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取实开周会信息
	 * @return
	 * @author: houyuhang
	 * @date: 2022/12/15
	 * @modify:
	 */
	@PostMapping(value="/queryMeetPerWeek")
	public ResponseResult<Object> queryMeetPerWeek(@RequestHeader(value = "Authorization") String token, @RequestBody(required = false) List<Map<String,Object>> projectList) {
		try {
			List<Map<String, Object>> res = mpmProjectService.queryMeetPerWeek(token, projectList);
			return ResponseResult.ok(res);
		}  catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取周会报表
	 * @return
	 * @author: houyuhang
	 * @date: 2022/12/15
	 * @modify:
	 */
	@GetMapping(value="/queryMeetStatInfo")
	public ResponseResult<Object> queryMeetStatInfo(@RequestHeader(value = "Authorization") String token, @RequestParam(required = false) Map<String,Object> paraMap) {
		try {
			// 将开始时间置为当周周一、结束时间置为当周周日
			if (paraMap.containsKey("startdate") && paraMap.containsKey("enddate")) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(ConvertUtil.convertToDate(paraMap.get("startdate")));
				paraMap.put("startdate", DateUtil.dateToString(ConvertTimeUtil.convertToThisWeekMonday(calendar).getTime(), "yyyy-MM-dd"));
				calendar.setTime(ConvertUtil.convertToDate(paraMap.get("enddate")));
				paraMap.put("enddate", DateUtil.dateToString(ConvertTimeUtil.convertToThisWeekSunday(calendar).getTime(), "yyyy-MM-dd"));
			}
			List<Map<String, Object>> res = mpmProjectService.queryMeetStatInfo(token, paraMap);
			Map<String, Object> resMap = new HashMap<>();
			resMap.put("dataList", res);
			return ResponseResult.ok(resMap);
		}  catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @description:导出会议统计Excel
	 * @author: houyuhang
	 * @date: 2023-03-07
	 * @modify:
	 */
	@PostMapping(value = "/meetExportExcel")
	public void meetExportExcel(@RequestHeader(value = "Authorization") String token, @RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 将开始时间置为当周周一、结束时间置为当周周日
			if (paraMap.containsKey("startdate") && paraMap.containsKey("enddate")) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(ConvertUtil.convertToDate(paraMap.get("startdate")));
				paraMap.put("startdate", DateUtil.dateToString(ConvertTimeUtil.convertToThisWeekMonday(calendar).getTime(), "yyyy-MM-dd"));
				calendar.setTime(ConvertUtil.convertToDate(paraMap.get("enddate")));
				paraMap.put("enddate", DateUtil.dateToString(ConvertTimeUtil.convertToThisWeekSunday(calendar).getTime(), "yyyy-MM-dd"));
			}
			List<Map<String, Object>> dataList = mpmProjectService.queryMeetStatInfo(token, paraMap);;
			String[] colArray = ConvertUtil.convertToString(paraMap.get("cols")).split(",");
			// 如果cols中包含项目经理字段，将项目经理放到部门后显示
			if (colArray[colArray.length - 1].contains(MpmProjectEntity.FieldProjectmanager)) {
				String temp = colArray[1];
				colArray[1] = colArray[colArray.length - 1];
				colArray[colArray.length - 1] = temp;
			}
			InputStream inStream = OfficeOperateUtil.exportExeclXlsx(dataList, colArray);
			String fileName = "会议统计.xlsx";
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			// 暴露自定义的首部,供页面资源使用
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}
	/***
	 * @description: 获取销售项目主表和sale表信息
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2023/03/28
	 * @modify:
	 */
	@GetMapping(value= "/queryProjectTotalInfo")
	public ResponseResult<Object> queryProjectTotalInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			if (paraMap.containsKey("projectcode")) {
				sql.appendSingle(" projectcode = '{0}' ", ConvertUtil.convertToString(paraMap.get("projectcode")));
			}
			List<Map<String, Object>> res = this.service.queryMapByWhere(sql.toString(), "queryPolymarizationMapByWhere");
			if (CollectionUtil.isEmpty(res)) {
				return ResponseResult.error("未查询到项目，请联系管理员！");
			}
			return ResponseResult.ok(res.get(0));
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取mpm标记信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@GetMapping(value= "/querySignInfo")
	public ResponseResult<Object> querySignInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			List<Map<String, Object>> dataList = baseOperateRecordService.querySignInfo(paraMap);
			return ResponseResult.ok(dataList);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 删除mpm标记信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@DeleteMapping(value= "/deleteSign")
	public ResponseResult<Object> deleteSign(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String ids = ConvertUtil.convertToString(paraMap.get("id"));
			baseOperateRecordService.deleteByWhere(" id in (" + ids + ")");
			return ResponseResult.ok("删除成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取mpm单条标记信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@GetMapping(value= "/loadSign")
	public ResponseResult<Object> loadSign(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Map<String, Object> dataMap = baseOperateRecordService.queryMapById(ConvertUtil.convertToString(paraMap.get("id")));
			if (!ObjectUtil.isEmpty(dataMap.get("operatedescription"))) {
				StringBufferProxy sql = new StringBufferProxy();
				sql.appendSingle(" enabled = 1 and instr(',' || '{0}' || ',', ',' || code || ',') > 0 ", ConvertUtil.convertToString(dataMap.get("operatedescription")));
				String username = cboUserService.queryByWhere(sql.toString()).stream().map(CboUserEntity::getName).collect(Collectors.joining(","));
				dataMap.put("dispoperatedescription", username);
			}
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 新增mpm标记信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@PostMapping(value= "/insertSign")
	public ResponseResult<Object> insertSign(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			paraMap.put("createuser", mpmProjectService.getSessionUserBean().getUser().getId());
			paraMap.put("modifieduser", mpmProjectService.getSessionUserBean().getUser().getId());
			paraMap.put("createorgid", mpmProjectService.getSessionUserBean().getOrg().getId());
			Map<String, Object> dataMap = baseOperateRecordService.insertSign(paraMap);
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 更新mpm标记信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@PutMapping(value= "/updateSign")
	public ResponseResult<Object> updateSign(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			baseOperateRecordService.update(paraMap);
			return ResponseResult.ok("保存成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取标记可选择人员（经营管理部所有成员）
	 * @return
	 * @author: houyuhang
	 * @date: 2023/01/10
	 * @modify:
	 */
	@GetMapping(value= "/querySignPeople")
	public ResponseResult<Object> querySignPeople(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Query query = new Query(paraMap);
			query.setPageSize(3000);
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" enabled = 1 ");
			// 筛选条件
			if (paraMap.containsKey("qry_code")) {
				String value = paraMap.get("qry_code").toString();
				if (!StringUtil.isEmpty(value))
					sql.appendSingle(" and code like '%{0}%' ", value);
			}
			if (paraMap.containsKey("qry_name")) {
				String value = paraMap.get("qry_name").toString();
				if (!StringUtil.isEmpty(value))
					sql.appendSingle(" and name like '%{0}%' ", value);
			}
			sql.appendSingle(" and code != '{0}' ", this.getUserBean().getUser().getCode());
			// 获取经营管理部deptcode
			String deptcode = ParameterCache.getValue("MpmJingyingDept");
			List<String> deptcodeList = Arrays.asList(deptcode.split(","));
			sql.appendSingle(" and deptid in (select id from cbodept where 1!=1 ");
			for (String temp : deptcodeList) {
				sql.appendSingle(" or code like '%{0}%' ", temp);
			}
			sql.appendSingle(" ) order by length(code) asc, code asc ");
			List<Map<String, Object>> result = cboUserService.queryMapByWhere(sql.toString());
			Page page = new Page(result, result.size(), query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}


	/**
	 * @Description:    获取所有人员
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           25/5/2023 下午8:57
	 * @Version:        1.0
	 **/
	@GetMapping(value= "/querySignPeopleForAll")
	public ResponseResult<Object> querySignPeopleForAll() {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" enabled = 1 and code != '{0}' and code in (select usercode from MPMPMOSTANDARDIZATIONRECORD) ", this.getUserBean().getUser().getCode());
			List<Map<String, Object>> result = cboUserService.queryMapByWhere(sql.toString());
			StringBufferProxy code = new StringBufferProxy();
			StringBufferProxy name = new StringBufferProxy();
			result.stream().forEach(m -> {
				code.appendSingle(m.get("code") + ",");
				name.appendSingle(m.get("name") + ",");
			});
			String resCode = ConvertUtil.convertToString(code);
			resCode = resCode.substring(0, resCode.length() -1);
			String resName = ConvertUtil.convertToString(name);
			resName = resName.substring(0, resName.length() -1);
			Map<String, String> resultforAll = new HashMap<String, String>();
			resultforAll.put("code",resCode);
			resultforAll.put("name",resName);
			return ResponseResult.ok(resultforAll);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 获取四张表表格内容
	 * @return
	 * @author: houyuhang
	 * @date: 2023/05/26
	 * @modify:
	 */
	@GetMapping(value= "/queryFourPageForm")
	public ResponseResult<Object> queryFourPageForm(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String sqlWhere = this.spellFourPageSql(paraMap);
			paraMap.put("whereSql", sqlWhere);
			Page page = mpmProjectService.queryFourPageForm(paraMap);
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/***
	 * @description: 拼接四张表sql
	 * @return
	 * @author: houyuhang
	 * @date: 2023/05/26
	 * @modify:
	 */
	public String spellFourPageSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		if (paraMap.containsKey("qry_projectmanager")) {
			String value = paraMap.get("qry_projectmanager").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (pro.projectmanager like '%{0}%' or pro.projectmanagercode like '%{0}%') ", value);
		}
		if (paraMap.containsKey("qry_projectlevel")) {
			String value = paraMap.get("qry_projectlevel").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and pro.projectlevel  in ({0})", value);
		}
		if (paraMap.containsKey("qry_deptcommoncode")) {
			String value = paraMap.get("qry_deptcommoncode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and pro.deptcommoncode in ({0}) ", value);
		}
		if (paraMap.containsKey("qry_projectname")) {
			String value = paraMap.get("qry_projectname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (pro.projectname like '%{0}%' or pro.projectcode like '%{0}%') ", value);
		}
		if (paraMap.containsKey("startdate") && paraMap.containsKey("enddate")) {
			String startdateSql = SQLAdapter.toDateLong(ConvertUtil.convertToString(paraMap.get("startdate")) + " 00:00:00");
			String enddateSql = SQLAdapter.toDateLong(ConvertUtil.convertToString(paraMap.get("enddate")) + " 23:59:59");
			String lastenddate = SQLAdapter.toDateLong("2099-12-25 23:59:59");
			sql.appendSingle(" and finishdate <= {0} and {1} > {2} ", enddateSql, SQLAdapter.isNull(MpmProjectEntity.FieldActualenddate, lastenddate), startdateSql);
		} else {
			sql.appendSingle(" and projectstate = '{0}' ", MpmSystemConst.ProjectState.ExecuteStateCode);
		}
		return sql.toString();
	}
	/**
	 * @description:导出项目报表统计Excel
	 * @author: houyuhang
	 * @date: 2023-05-31
	 * @modify:
	 */
	@PostMapping(value = "/fourPageExportExcel")
	public void fourPageExportExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			String sqlWhere = this.spellFourPageSql(paraMap);
			paraMap.put("whereSql", sqlWhere);
			Page page = mpmProjectService.queryFourPageForm(paraMap);
			String[] colArray = ConvertUtil.convertToString(paraMap.get("cols")).split(",");
			InputStream inStream = OfficeOperateUtil.exportExeclXlsx((List<Map<String, Object>>) page.getDataList(), colArray);
			String fileName = "项目报表统计.xlsx";
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			// 暴露自定义的首部,供页面资源使用
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}
}
